<template>
	<div ref="logContainer" class="monaco-editor-container"></div>
	<a-drawer
		title="输出"
		placement="right"
		:width="500"
		:z-index="9999"
		:closable="true"
		:mask="true"
		v-model:open="config.openOutputResultFlag"
	>
		<div ref="resultViewContainer" style="width: 100%; height: 600px"></div>
	</a-drawer>
</template>

<script setup>
	import * as monaco from 'monaco-editor'
	import JsonEditor from 'jsoneditor'
	import 'jsoneditor/dist/jsoneditor.min.css'

	const props = defineProps(['lf', 'logCardStyle'])

	const logContainer = ref()
	const resultViewContainer = ref()
	let logEditor = null
	let resultViewJsonEditor = null

	const config = ref({
		openOutputResultFlag: false
	})
	onMounted(() => {
		initLogEditor()
	})

	const appendLog = (d) => {
		const logStr = props.lf.logAndStepStatusFormat(d)
		console.log(logStr)
		if (d.type == 'log') {
			if (logStr) {
				appendLogToView(logStr)
			}
		} else if (d.type == 'result') {
			appendLogToView(`执行结束 结果:${JSON.stringify(logStr) || ''}`)
			resultToView(logStr)
		} else if (d.type == 'error') {
			if (logStr) {
				appendLogToView(`执行异常>>>${logStr || ''}`)
			}
		}
	}

	const resultToView = (result) => {
		config.value.openOutputResultFlag = true

		if (!resultViewJsonEditor) {
			initResultViewJsonEditor()
		} else {
			resultViewJsonEditor.set({})
		}
		nextTick(() => {
			resultViewJsonEditor.set(result)
		})
	}

	const initResultViewJsonEditor = () => {
		const options = {
			modes: ['code', 'tree', 'form', 'text', 'preview'],
			mode: 'code'
		}
		nextTick(() => {
			resultViewJsonEditor = new JsonEditor(resultViewContainer.value, options)
			resultViewJsonEditor.set({})
		})

		// const initJson = {};
		// editor.value.set(initJson);
	}

	const appendLogToView = (log) => {
		try {
			// 简化字符过滤，只移除真正的控制字符
			log = log.replace(/[\0-\x1F\x7F]/g, '')
			log = log + '\n'


			if (!logEditor) {
				console.error('编辑器未初始化')
				return
			}

			// 使用 setValue 方法更可靠地添加内容
			const currentValue = logEditor.getValue()
			const newValue = currentValue + log

			// 设置新内容
			logEditor.setValue(newValue)

			// 滚动到最后一行
			const lineCount = logEditor.getModel().getLineCount()
			logEditor.revealLine(lineCount)

			// 设置光标到最后
			logEditor.setPosition({ lineNumber: lineCount, column: 1 })


		} catch (error) {
			// 尝试使用备用方法
			try {
				logEditor.focus()
				const position = logEditor.getPosition()
				logEditor.executeEdits('', [
					{
						range: {
							startLineNumber: position.lineNumber,
							startColumn: position.column,
							endLineNumber: position.lineNumber,
							endColumn: position.column
						},
						text: log
					}
				])
				logEditor.focus()
				logEditor.revealLine(logEditor.getModel().getLineCount())
			} catch (backupError) {
				console.error('备用方法也失败:', backupError)
			}
		}
	}

	const initLogEditor = () => {
		// monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
		// 	validate: false
		// })

		logEditor = monaco.editor.create(logContainer.value, {
			theme: 'vs-dark', // 主题
			value: '', // 默认显示的值
			language: 'log',
			folding: true, // 是否折叠
			foldingHighlight: true, // 折叠等高线
			foldingStrategy: 'indentation', // 折叠方式  auto | indentation
			showFoldingControls: 'always', // 是否一直显示折叠 always | mouseover
			disableLayerHinting: true, // 等宽优化
			emptySelectionClipboard: false, // 空选择剪切板
			selectionClipboard: false, // 选择剪切板
			automaticLayout: true, // 自动布局
			codeLens: false, // 代码镜头
			scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
			colorDecorators: true, // 颜色装饰器
			accessibilitySupport: 'off', // 辅助功能支持  "auto" | "off" | "on"
			lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
			lineNumbersMinChars: 5, // 行号最小字符   number
			enableSplitViewResizing: false,
			readOnly: false, //是否只读  取值 true | false
			wordWrap: 'on', // 启用自动换行
			minimap: {
				enabled: true
			},
			fontSize: 14,
			fontFamily: 'Menlo, Monaco, Consolas, "Courier New", monospace',
			lineHeight: 22,
		})


		// 检查 DOM 结构
		setTimeout(() => {
			// 强制重新布局
			logEditor.layout()
		}, 1000)
	}
	const clearLog = () => {
		logEditor.setValue('')
	}
	defineExpose({
		appendLog,
		clearLog
	})
</script>

<style scoped lang="scss">
.monaco-editor-container {
	width: 100%;
	height: 100%;
	min-height: 200px;
	position: relative;
	background: #1e1e1e;
	border-radius: 4px;
	border: 1px solid #333;
	overflow: hidden;
	/* 让编辑器自适应容器 */
	display: flex;
	flex-direction: column;
}

/* 强制显示 Monaco Editor 相关元素 */
:deep(.monaco-editor),
:deep(.monaco-editor *),
:deep(div[class*="monaco"]),
:deep(div[class*="monaco"] *) {
	display: flex !important;
	visibility: visible !important;
	opacity: 1 !important;
}

</style>
